/**
 * 
 */

package de.unihannover.se.restlab.microblog.resources;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.Consumes;
import javax.ws.rs.FormParam;
import javax.ws.rs.GET;
import javax.ws.rs.HeaderParam;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriInfo;

import de.unihannover.se.restlab.microblog.data.AuthService;
import de.unihannover.se.restlab.microblog.data.MessageStorage;
import de.unihannover.se.restlab.microblog.data.UserStorage;
import de.unihannover.se.restlab.microblog.models.Link;
import de.unihannover.se.restlab.microblog.models.Message;
import de.unihannover.se.restlab.microblog.models.User;

@Path("messages")
public class MessageListResource {
	@Context
	HttpServletRequest request;

	@Context
	UriInfo ui;

	@GET
	@Produces({MediaType.TEXT_PLAIN, MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
	public Response list () {
		List<Message> messages = MessageStorage.getStorage().getMessages();

		for (Message msg : messages) {
			Link self = new Link(ui.getAbsolutePathBuilder().path("{id}").build(msg.getId()).toString(), "self");
			msg.setSelf(self);
		}

// List<User> users = UserStorage.getUsers();
// for (User user : users) {
// Link self = new Link(ui.getAbsolutePathBuilder().path("{id}").build(user.getId()).toString(), "self");
// user.setSelf(self);
// }

		return Response.ok(messages.toArray(new Message[] {})).build();
	}

	@POST
	@Produces({MediaType.TEXT_PLAIN, MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
	@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
	public Response create (@FormParam("userId") Integer userId, @FormParam("content") String content,
		@FormParam("parentId") Integer parentId, @HeaderParam("Authorization") String authHeader) {
		
		//String authHeader = request.getHeader("Authorization");
		if (authHeader == null) { // Auhtorizaiton-Header angegeben?
			return Response.status(401).header("www-Authenticate", "Basic realm=\"Account-Liste: Auhtorization required\"").build();
			// Admins kann immer Nachrichten für jeden erstellen, normale Nutzer nur für sich selbst. :3
		} else if (!AuthService.isUserAuthenticatedAndHasId(request, userId) && !AuthService.isUserAuthenticatedAndAdmin(request)) {
			return Response.status(401).header("www-Authenticate", "Basic realm=\"Account-Liste: User or Password incorrect\"")
				.build();
		} else {
			User user = UserStorage.getStorage().getUser(userId);
			Message message = MessageStorage.getStorage().createMessage(user, content, parentId);
			return Response.ok(message).build();
		}
		// return Response.ok(message).build();
	}

	@Path("{id}")
	public MessageResource getMessageResource (@PathParam("id") Integer id) {
		return new MessageResource(id);
	}

}
